package network.course5Http.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpClient {
    public static String  doGet(String httpUrl){
        HttpURLConnection httpURLConnection=null;
        InputStream in=null;
        BufferedReader br=null;
        String result=null;//返回结果的字符串

        try {
            //创建远程URL连接对象
            URL url=new URL(httpUrl);
            //通过远程URL连接对象打开一个连接，强制转成HTTPSURLConnection类
            httpURLConnection= (HttpURLConnection) url.openConnection();
            //设置连接方式：get
            httpURLConnection.setRequestMethod("GET");
            //设置连接主机服务器的超时时间15000毫秒
            httpURLConnection.setConnectTimeout(15000);
            //设置读取返回的时间60000毫秒
            httpURLConnection.setReadTimeout(60000);
            //发送请求
            httpURLConnection.connect();

            if (httpURLConnection.getResponseCode()==200){
                //通过连接，获取输入流
                in=httpURLConnection.getInputStream();
                //封装输入流in，并指定字符集
                br=new BufferedReader(new InputStreamReader(in,"UTF-8"));
                //存放数据
                StringBuffer sb=new StringBuffer();
                String temp=null;
                while((temp=br.readLine())!=null){
                    sb.append(temp);
                    sb.append("\r\n");


                }
                result=sb.toString();

            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            if (br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭输入流
            if (in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭远程连接
            httpURLConnection.disconnect();
        }

        return result;
    }

    public static void main(String[] args) {
        System.out.println(doGet("http://www.265g.com"));
    }
}
